package com.qiantu.phone.ui.dialog;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.base.BaseDialog;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.event.RefreshSceneIntentEvent;
import com.qiantu.phone.ui.adapter.SceneIntentListAdapter;
import com.qiantu.phone.manager.CenterFlowLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import okhttp3.Call;

public class SceneIntentDialog {

    public static final class Builder
            extends BaseDialog.Builder<SceneIntentDialog.Builder> {

        private RecyclerView mRecyclerView;
        private SceneIntentListAdapter mSceneIntentListAdapter;
        private List<SceneBean> data;
        private String sceneSerialNo;
        private float mTouchDownX;
        private float mTouchDownY;
        private float clickThreshold;

        public Builder(Context context) {
            super(context);
            setContentView(R.layout.dialog_scene_intent);
            mRecyclerView = findViewById(R.id.recycler_view);
            clickThreshold = getResources().getDimension(R.dimen.dp_2);
            mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
            if (mSceneIntentListAdapter == null) {
                int imageListWidth = DensityUtils.getScreenWidth(getContext()) - mRecyclerView.getPaddingLeft() - mRecyclerView.getPaddingRight();
                mSceneIntentListAdapter = new SceneIntentListAdapter(imageListWidth / 3);
                if (data != null) {
                    mSceneIntentListAdapter.setNewInstance(data);
                }
                mRecyclerView.setAdapter(mSceneIntentListAdapter);
                mSceneIntentListAdapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                        SceneBean scene = mSceneIntentListAdapter.getData().get(position);
                        LLHttpManager.sceneOperation((LifecycleOwner) getContext(), scene.getSceneSerialNo(), new HttpCallback<HttpData<Void>>(null) {
                            @Override
                            public void onStart(Call call) {
                                if (getContext() != null && getContext() instanceof AppActivity) {
                                    ((AppActivity) getContext()).showDialog();
                                }
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                super.onSucceed(result);
                                ToastUtils.show("执行成功");
                                dismiss();
                            }

                            @Override
                            public void onFail(Exception e) {
                                ToastUtils.show(R.string.exec_failure);
                            }

                            @Override
                            public void onEnd(Call call) {
                                if (getContext() != null && getContext() instanceof AppActivity) {
                                    ((AppActivity) getContext()).hideDialog();
                                }
                            }
                        });
                    }
                });
            }

            mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            mTouchDownX = event.getX();
                            mTouchDownY = event.getY();
                            break;
                        case MotionEvent.ACTION_UP:
                            float upX = event.getX();
                            float upY = event.getY();
                            float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mTouchDownX), 2) + Math.pow(Math.abs(upY - mTouchDownY), 2));
                            if (clickDistance <= clickThreshold) {
                                dismiss();
                            }
                            break;
                    }
                    return false;
                }
            });

            addOnDismissListener(new BaseDialog.OnDismissListener() {
                @Override
                public void onDismiss(BaseDialog dialog) {
                    EventBus.getDefault().unregister(SceneIntentDialog.Builder.this);
                }
            });

            addOnShowListener(new BaseDialog.OnShowListener() {
                @Override
                public void onShow(BaseDialog dialog) {
                    EventBus.getDefault().register(SceneIntentDialog.Builder.this);
                }
            });
        }

        public SceneIntentDialog.Builder setData(String sceneSerialNo, List<SceneBean> data) {
            this.sceneSerialNo = sceneSerialNo;
            this.data = data;
            if (mSceneIntentListAdapter != null) {
                mSceneIntentListAdapter.setNewInstance(data);
            }
            return this;
        }

        @Override
        public BaseDialog create() {
            BaseDialog baseDialog = super.create();
            return baseDialog;
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onRefreshSceneIntentEvent(RefreshSceneIntentEvent event) {
            //监听场景意图数据刷新，导致当前显示意图没有了，关闭dialog
            List<SceneBean> data = LLSceneDBManager.getInstance(getContext()).getScenesIntentBySerialNo(sceneSerialNo);
            if(data == null || data.size() == 0){
                dismiss();
            }
        }
    }
}
